﻿using PixivGifDownLoad.Helper;
using System;

using System.Windows.Forms;
using System.Net;

using System.IO;
using System.ComponentModel;
using AnimatedGif;
using System.Drawing;
using System.IO.Compression;
using System.Linq;
using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;
using Newtonsoft.Json;
using PixivGifDownLoad.Helper.PixivHelper;
using CatUtilsDll.Utils.Currency.WebUtils;

namespace PixivGifDownLoad
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
            InitData();
            form1 = this;
        }

        public static MainForm form1;
        private static String Localurl = "";
        private static String FilePath = "";

        private static Timer timer2 = new Timer();

        /// <summary>
        /// 图片色阶转化方式
        /// </summary>
        private static GifQuality quality = GifQuality.Bit8;

        private void InitData()
        {
            timer2.Tick += timer2_Tick;
            timer2.Enabled = true;
            timer2.Interval = 500;

            timer2.Stop();
            FloderHelper.FloderExits(PixivStaticValue.TempPath, true);
            FloderHelper.FloderExits(PixivStaticValue.GifPath1, true);
            pictureBox1.Image = Resource1.Logo;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer2.Start();

            RunNext();
        }

        private void CallProgressCount(object sender, DownloadProgressChangedEventArgs e)
        {
            label2.Text = "当前解析进度：" + e.ProgressPercentage;
            progressBar2.Value = e.ProgressPercentage;
            Console.WriteLine(e.ProgressPercentage);
        }

        private void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string shtml = e.Result;
                Console.WriteLine(shtml);
                PixivGifJson.Root GIFValue = JsonConvert.DeserializeObject<PixivGifJson.Root>(shtml);

                string GifUrl = GetGifUrl(GIFValue);
                if (form1.checkBox1.Checked)
                    form1.textBox2.Text = GetGifTime(GIFValue);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
        }

        /// <summary>
        /// 获取GIF延迟时间
        /// </summary>
        /// <param name="GIFValue"></param>
        /// <returns></returns>
        private string GetGifTime(PixivGifJson.Root GIFValue)
        {
            string Time = "";
            try
            {
                if (GIFValue.body.frames.Count > 0)
                    return GIFValue.body.frames[0].delay.ToString();
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return Time;
        }

        private static string GetGifUrl(PixivGifJson.Root GIFValue)
        {
            String url = "";
            try
            {
                url = GIFValue.body.originalSrc;
                Localurl = GIFValue.body.src.Replace("ugoira600x600", "ugoira1920x1080");
                FilePath = PixivStaticValue.TempPath + Path.GetFileName(Localurl);
                PixivWebHelper.FileDownLoad(Localurl, DownProgress, DownCompletedAsync);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                PrintLog.Log("该链接不是正常GIF，已经自动跳过");
                RunNext();
            }
            return url;
        }

        private static void DownProgress(object sender, DownloadProgressChangedEventArgs e)
        {
            Console.WriteLine(e.ProgressPercentage);
            PixivStaticValue.count = e.ProgressPercentage;
            PixivStaticValue.tip = string.Format("已下载{0}%，剩余{1}KB", e.ProgressPercentage, (int)(e.TotalBytesToReceive - e.BytesReceived + 1) / 1024);
        }

        private static async void DownCompletedAsync(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (e.Error.ToString().IndexOf("404") > 0)
                {
                    Console.WriteLine("未找到文件,重启下载");
                    if (Localurl != "")
                    {
                        FilePath = PixivStaticValue.TempPath + Path.GetFileName(Localurl);
                        PixivWebHelper.FileDownLoad(Localurl, DownProgress, DownCompletedAsync);
                        Localurl = "";//释放
                    }
                    else
                    {
                        PrintLog.Log("连续两次下载出错，放弃！");
                        return;
                    }
                    return;
                }
                else
                {
                    PrintLog.Log(e.Error);
                }
            }
            Console.WriteLine("下载已完成");

            RunCreateAsync();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", PixivStaticValue.GifPath1);
        }

        private static async System.Threading.Tasks.Task RunCreateAsync()
        {
            Console.WriteLine(FilePath);
            int GifTime = 50;
            if (form1.textBox2.Text != "")
            {
                try
                {
                    GifTime = Convert.ToInt32(form1.textBox2.Text);
                }
                catch (Exception ex)
                {
                    PrintLog.Log(ex);
                    PrintLog.Log("获取时间长度错误");
                    MessageBox.Show(ex.Message);
                    return;// 拒绝错误数据
                }
                Console.WriteLine(GifTime);
                Console.WriteLine(quality);
                String cat = await CreateGif.LoadFromZipAsync(FilePath, GifTime, quality);
                Console.WriteLine("已完成 ");
            }
            else
                MessageBox.Show("时间间隔不能为空！");
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (progressBar1.Value != PixivStaticValue.count)
            {
                progressBar1.Value = PixivStaticValue.count;
                label1.Text = PixivStaticValue.tip;
            }
            if (PixivStaticValue.JpgLock1)
            {
                Console.WriteLine("任务完成，内存释放");
                // timer2.Enabled = true;
                //   timer2.Stop();
                PixivStaticValue.JpgLock1 = false;
                PixivStaticValue.JpgCount1 = 0;
                PixivStaticValue.JpgMaxCount1 = 0;
                progressBar1.Value = 0;
                progressBar2.Value = 0;
                progressBar3.Value = 0;
                PixivStaticValue.count = 0;
                label2.Text = "当前无待解析。";
                label1.Text = "当前无待下载";
                label3.Text = "图片已经创建，请点击图片文件夹进行查看。";
                RunNext();
            }
            progressBar3.Maximum = PixivStaticValue.JpgMaxCount1;
            progressBar3.Value = PixivStaticValue.JpgCount1;
            label3.Text = string.Format("总计{0}帧，当前已插入{1}帧", PixivStaticValue.JpgMaxCount1, PixivStaticValue.JpgCount1);
        }

        private static void RunNext()
        {
            Console.WriteLine(form1.richTextBox1.Lines.Count());
            if (form1.richTextBox1.Lines.Count() > 0)
            {
                string ArtID = TextHelper.GetFirstVlaue(form1.richTextBox1.Lines);
                ArtID = CreateGif.GetId(ArtID);
                Console.WriteLine("图片ID" + ArtID);
                form1.richTextBox1.Lines = form1.richTextBox1.Lines.Skip(1).ToArray();
                if (ArtID != "")
                {
                    WebHelper.HttpGetAsync($"https://www.pixiv.net/ajax/illust/{ArtID}/ugoira_meta", form1.DownloadCompleted, form1.CallProgressCount);

                    //删除第一行
                }
                else
                    RunNext();
                return;
            }
            else
            {
                Console.WriteLine("所有任务完成！");
                form1.richTextBox1.Text = "";
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            quality = CreateGif.GetQuality(comboBox1.Text);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            Console.WriteLine("已更改");
            if (!checkBox1.Checked)
            {
                DialogResult dr = MessageBox.Show("请您正确的设置GIF切换的时间，我并不推荐您修改此项。", "更改GIF时间", MessageBoxButtons.OKCancel);
                if (dr == DialogResult.OK)
                {
                }
                else if (dr == DialogResult.Cancel)
                {
                    //用户选择取消的操作
                    checkBox1.Checked = true;
                }
            }
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
        }

        private void richTextBox1_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = richTextBox1.Text + "\r\n";
            richTextBox1.Select(richTextBox1.Text.Length, 0);
        }

        private void label6_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.acg12.net/?p=6796");
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://acgsoso.com/");
        }
    }
}